/**
 * @description: 商品分类
 * @author: pengzhenjin
 * @date: 2020/7/21
 */
import React, {Component} from 'react';
import {
  StyleSheet,
  View,
  Text,
  StatusBar,
  Image,
  TouchableOpacity,
  FlatList,
  SectionList,
  Dimensions,
} from 'react-native';
import Navigation from '../../utils/Navigation';
import {super_classify} from '../../api/haoDan';
import EventBus from '../../utils/EventBus';
const {width, height} = Dimensions.get('window');

const firstCategoryItemHeight = 56;

export default class GoodsCategory extends Component {
  static navigationOptions = {
    title: '分类',
    tabBarOnPress: (event) => {
      //调用组建内默认的实现方法
      event.defaultHandler();
      EventBus.emit('douying');
    },
  };

  constructor(props) {
    super(props);
    this.state = {
      firstCategoryData: [], // 一级分类数据
      secondCategoryData: [], // 二级分类数据
      selectedFirstCategoryIndex: 0, // 选中的一级分类的索引
    };
  }

  componentDidMount() {
    this.initData();
  }

  initData = () => {
    const firstCategoryData = [];
    const secondCategoryData = [];
    super_classify().then((res) => {
      if (res != null) {
        res.map((item, index) => {
          firstCategoryData.push({
            id: index,
            name: item.main_name,
            data: item.data,
          });
        });
      }
      secondCategoryData.push(firstCategoryData[0]);
      this.setState({
        firstCategoryData: firstCategoryData,
        secondCategoryData: secondCategoryData,
      });
    });
  };

  setFirstItemIndex = (index) => {
    const secondCategoryData = [];
    secondCategoryData.push(this.state.firstCategoryData[index]);
    this.setState({
      selectedFirstCategoryIndex: index,
      secondCategoryData: secondCategoryData,
    });

    // 计算当前 item 的高度
    const indexHeight = firstCategoryItemHeight * index;

    // 计算屏幕一半的高度
    const halfHeight = (height - 65) / 2;

    if (indexHeight > halfHeight) {
      this.flatList.scrollToOffset({
        animated: true,
        offset: indexHeight - halfHeight,
      });
    }
  };

  onClickFirstCategoryItem = (item, index) => {
    this.setFirstItemIndex(index);
  };

  renderFirstCategoryItem = ({item, index}) => {
    const selectedFirstCategoryIndex = this.state.selectedFirstCategoryIndex;

    let itemContainerStyle;
    let itemTextColor;
    if (selectedFirstCategoryIndex === index) {
      itemContainerStyle = styles.first_category_item_selected_container;
      itemTextColor = '#FA7B00'; //'#FA7B00';
    } else {
      itemContainerStyle = styles.first_category_item_container;
      itemTextColor = '#333333';
    }

    return (
      <TouchableOpacity
        key={index}
        style={itemContainerStyle}
        onPress={() => {
          this.onClickFirstCategoryItem(item, index);
        }}>
        <Text style={[styles.first_category_item_text, {color: itemTextColor}]}>
          {item.name}
        </Text>
      </TouchableOpacity>
    );
  };

  renderSecondCategoryItem = (item) => {
    if (item.index === 0) {
      const data = item.section.data;
      return (
        <View style={styles.second_Item_Contain}>
          {data.map((item, index) => {
            return (
              <View key={index}>
                <Text
                  style={styles.second_category_item_title}
                  numberOfLines={1}>
                  {item.next_name}
                </Text>
                <View style={styles.second_category_item_container1}>
                  {item.info.map((subItem, index) => {
                    return (
                      <TouchableOpacity
                        key={index}
                        style={styles.second_category_item_container2}
                        onPress={() => {
                          var keyword = subItem.son_name;
                          console.log(keyword);
                          Navigation.navigate('SearchList', {keyword});
                        }}>
                        <Image
                          style={styles.second_category_item_image}
                          source={{uri: subItem.imgurl}}
                        />
                        <Text
                          style={styles.second_category_item_title}
                          numberOfLines={1}>
                          {subItem.son_name}
                        </Text>
                      </TouchableOpacity>
                    );
                  })}
                </View>
              </View>
            );
          })}
        </View>
      );
    } else {
      return null;
    }
  };

  renderSecondCategorySectionHeader = ({section}) => {
    return (
      <View
        style={{
          backgroundColor: '#fbfbfb',
          height: 30,
          justifyContent: 'center',
          alignItems: 'center',
        }}>
        <Text style={styles.second_category_section_title}>{section.name}</Text>
      </View>
    );
  };

  renderSeparatorLine = () => {
    return <View style={styles.separator_line} />;
  };

  render() {
    return (
      <View style={{flex: 1, flexDirection: 'column'}}>
        <SearchBar />
        <View style={styles.container}>
          <View style={styles.first_category_container}>
            <FlatList
              ref={(refs) => (this.flatList = refs)}
              keyExtractor={(item, index) => index.toString()}
              data={this.state.firstCategoryData}
              renderItem={this.renderFirstCategoryItem}
              ItemSeparatorComponent={this.renderSeparatorLine}
            />
          </View>
          <View style={styles.second_category_container}>
            {this.state.secondCategoryData.length <= 0 ? (
              <View />
            ) : (
              <SectionList
                // ItemSeparatorComponent={() => <View style={{backgroundColor:'red',height:1}}></View>}  //分割线
                ref={(refs) => (this.sectionList = refs)}
                renderSectionHeader={this.renderSecondCategorySectionHeader}
                renderItem={this.renderSecondCategoryItem}
                sections={this.state.secondCategoryData}
                ItemSeparatorComponent={null}
                ListHeaderComponent={null}
                ListFooterComponent={null}
                keyExtractor={(item, index) => index + item}
                stickySectionHeadersEnabled={true}
                //   initialNumToRender={this.state.listNum / 4}
                //   onViewableItemsChanged={(info) => this.itemChange(info)} //滑动时调用
              />
            )}
          </View>
        </View>
      </View>
    );
  }
}

const SearchBar = () => {
  return (
    <View style={styles.search_bar}>
      <TouchableOpacity
        activeOpacity={1}
        style={styles.search_bar_body}
        onPress={() => Navigation.navigate('SearchIndex')}>
        <Text style={styles.search_bar_input}>输入关键词或粘贴淘宝标题</Text>
      </TouchableOpacity>
    </View>
  );
};

const styles = StyleSheet.create({
  search_bar: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#FFF',
    paddingTop: StatusBar.currentHeight,
    paddingHorizontal: 20,
  },
  search_bar_body: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#E4E4E4',
    height: 30,
    marginVertical: 10,
    borderRadius: 19,
    paddingLeft: 10,
    marginRight: 10,
  },
  search_bar_input: {
    fontSize: 12,
    paddingLeft: 10,
    lineHeight: 38,
    color: '#898989',
  },
  container: {
    flex: 1,
    flexDirection: 'row',
  },
  first_category_container: {
    flexDirection: 'column',
    width: 90,
  },
  first_category_item_container: {
    height: firstCategoryItemHeight,
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: 14,
    backgroundColor: '#FFFFFF',
  },
  first_category_item_selected_container: {
    height: firstCategoryItemHeight,
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: 14,
    borderLeftWidth: 4,
    borderColor: '#FA7B00',
    backgroundColor: 'transparent',
  },
  first_category_item_text: {
    fontSize: 14,
    color: '#333333',
  },
  second_category_container: {
    flex: 1,
    flexDirection: 'column',
  },

  second_Item_Contain: {
    flex: 1,
    flexDirection: 'column',
  },

  second_category_item_container1: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    backgroundColor: '#FFFFFF',
    borderRadius: 5,
    marginHorizontal: 14,
  },
  second_category_item_container2: {
    width: (width - 118) / 3,
    marginVertical: 15,
    justifyContent: 'center',
    alignItems: 'center',
  },
  second_category_item_image: {
    width: 65,
    height: 65,
  },
  second_category_item_title: {
    // marginTop: 16,
    height: 20,
    fontSize: 14,
    color: '#333333',
  },
  second_category_section_title: {
    fontSize: 14,
    color: '#333333',
    fontWeight: 'bold',
    // marginHorizontal: 15,
    // marginTop: 20,
    // marginBottom: 15,
  },
  separator_line: {
    flex: 1,
    flexDirection: 'row',
    height: 1,
    backgroundColor: '#E4E4E4',
    marginHorizontal: 14,
  },
});
